#pragma once

#include <iostream>
#include <cstdlib>
#include <functional>
#include <strings.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "InetAddr.hpp"

using callback_t = std::function<void \
        (int sockfd, const std::string message, InetAddr addr)>;

static const int g_socket_fd = -1;

class ChatServer
{
public:
    ChatServer(uint16_t port, callback_t cb)
        : _port(port),
          _socket_fd(g_socket_fd),
          _is_running(false),
          _cb(cb)
    {
    }
    void Init()
    {
        // 1、创建套接字
        _socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socket_fd < 0)
        {
            LOG(LogLevel::ERROR) << "create socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "create socket success : " << _socket_fd;

        // 2、绑定
        InetAddr local(_port);

        // 2.2 socket和file进行bind
        int n = bind(_socket_fd, local.Addr(), local.Length());
        if(n < 0)
        {
            LOG(LogLevel::ERROR) << "bind socket error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket success : " << _socket_fd;

    }
    void Start()
    {
        //所有的服务器都是死循环
        _is_running = true;
        while(_is_running)
        {
            char buffer[1024];
            buffer[0] = 0;
            struct sockaddr_in peer;//数据发送方的socket数据
            socklen_t len = sizeof(peer);

            //1、读取数据
            //消息内容 + 发送主体
            ssize_t n = recvfrom(_socket_fd, buffer, sizeof(buffer), 0,
             (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                //聊天消息
                buffer[n] = 0;
                //获取client的socket
                InetAddr clientaddr(peer);
                LOG(LogLevel::DEBUG) << "get a client info # "
                    << clientaddr.Ip() << "-" << clientaddr.Port() << ": " <<buffer;
               
                std::string message = buffer;
                //回调
                //哪个客户端的信息通过哪个文件转发
                _cb(_socket_fd, message, clientaddr);//执行任务
  
            }
        }
        _is_running = false;  
    }
    void Stop()
    {
        _is_running = false;
    }
    ~ChatServer()
    {
    }

private:
    int _socket_fd;  // 文件描述符做返回值
    callback_t _cb;//服务器的工作
    uint16_t _port;  // 端口号
    bool _is_running;
};